package com.atguigu.admin.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * ClassName: FormTestController
 * Package: com.atguigu.admin.controller
 * Description:
 *文件上传测试
 * @Author Root
 * @Create 2023/4/4 15:41
 * @Version 1.0
 */
@Slf4j
@Controller
public class FormTestController {

    @GetMapping({"/form_layouts","/form_layouts.html"})
    public String form_layouts(){

        return "form/form_layouts";
    }

    /**
     *
     * @param email
     * @param username
     * @param headerImg 自动封装上传的文件
     * @param photos
     * @return
     */
    @PostMapping({"/upload"})
    public String upload(@RequestParam("email")String email,
                         @RequestParam("username") String username,
                         @RequestPart("headerImg")MultipartFile headerImg,
                         @RequestPart("photos")MultipartFile[] photos) throws IOException {
        log.info("上传的信息email:{}",email);
        log.info("上传的信息username:{}",username);
        log.info("上传的信息headerImg:{}",headerImg.getSize());
        log.info("上传的信息photos:{}",photos.length   );

        if(!headerImg.isEmpty()){
            //保存到文件服务器，OSS服务器
            String originalFilename = headerImg.getOriginalFilename();
            String uuid = UUID.randomUUID().toString();
            //获取文件后缀名
            String hzName = originalFilename.substring(originalFilename.lastIndexOf("."));
            log.info("uuid:{}",uuid);
            originalFilename=uuid+hzName;
            headerImg.transferTo(new File("D:\\develop\\springboot2\\boot-05-web-admin\\pictures\\"+originalFilename));
        }

        if (photos.length>0){
            for (MultipartFile photo : photos) {
                if (!photo.isEmpty()){
                    String originalFilename = photo.getOriginalFilename();
                    String uuid = UUID.randomUUID().toString();
                    //获取文件后缀名
                    String hzName = originalFilename.substring(originalFilename.lastIndexOf("."));
                    log.info("uuid:{}",uuid);
                    originalFilename=uuid+hzName;
                    photo.transferTo(new File("D:\\develop\\springboot2\\boot-05-web-admin\\pictures\\"+originalFilename));
                }
            }
        }


        return "form/form_layouts";
    }



}
